//
//  XKPageView.m
//  XKObjPageView
//
//  Created by 徐凯 on 2017/6/15.
//  Copyright © 2017年 XK. All rights reserved.
//

#import "XKPageView.h"
#import "XKPageStyle.h"

@interface XKPageView ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) XKPageStyle *style;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *childVCs;
@property (nonatomic, strong) UIViewController *parentVc;

@property (nonatomic, strong) UIScrollView *titleScrollView;
@property (nonatomic, strong) UILabel *selectLab;

@property (nonatomic, strong) UICollectionView *contentCollextView;
@property (nonatomic, strong) NSMutableArray *labAry;
@property (nonatomic ,strong) UIView *bottomLine;
@end

@implementation XKPageView

static NSString *ID = @"kContentCellID";

-(instancetype) initWithFrame:(CGRect)frame titles:(NSArray *) titles childVCs:(NSArray *) childVCs style:(XKPageStyle *) style parentVc:(UIViewController *) parentVc
{
    if(self = [super initWithFrame:frame])
    {
        _style = style;
        _titles = titles;
        _childVCs = childVCs;
        _parentVc = parentVc;
        [self setupUI];
    }
    
    return self;
}

-(void) setupUI
{
    [self setupContentView];
    [self setupTitleScrollView];

}

-(void) setupTitleScrollView
{
    _titleScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, _style.titleViewHeight)];
    _titleScrollView.showsHorizontalScrollIndicator = NO;

    [self addSubview:_titleScrollView];
    _titleScrollView.backgroundColor = [UIColor whiteColor];
    
    if(_style.isShoeBottomLine)
    {
        _bottomLine = [[UIView alloc] initWithFrame:CGRectMake(0, _style.titleViewHeight - 2, 0, 2)];
        _bottomLine.backgroundColor =_style.bottomLineColor;
        [_titleScrollView addSubview:_bottomLine];
    }
    
    
    _labAry = [NSMutableArray array];
    for(int i = 0; i< _titles.count; i++)
    {
        UILabel *lab = [[UILabel alloc] init];
        lab.text = _titles[i];
        lab.textColor = _style.titleNormalColor;
        lab.textAlignment = NSTextAlignmentCenter;
        lab.tag = i;
        lab.font = _style.titleFont;
        [_titleScrollView addSubview:lab];
        lab.userInteractionEnabled = YES;
        [_labAry addObject:lab];
       
    }
    
    
    for(int i =0; i<_titles.count; i++)
    {
        CGFloat w = 0;
        CGFloat h = _titleScrollView.frame.size.height;
        CGFloat y = 0;
        CGFloat x = 0;
        CGFloat sp = 20;

        if(_titles.count < 5)
        {
            w = _titleScrollView.frame.size.width / _titles.count;
            x = i * w;
        }
        else
        {
            NSString *t = _titles[i];
            CGRect rect = [t boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : _style.titleFont} context:nil];
            w = rect.size.width + 10;
            
            if(i == 0)
            {
                x = sp;
            }
            else
            {
                UILabel *fLab = _labAry[i - 1];

                x = fLab.frame.origin.x + fLab.frame.size.width + sp;
            }
            
        }
        
        UILabel *lab = _labAry[i];
        lab.frame = CGRectMake(x, y, w, h);
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleLabClick:)];
        [lab addGestureRecognizer:tap];
        
        if(i == 0)
        {
            [self titleLabClick:tap];
        }
        
        _titleScrollView.contentSize = CGSizeMake(lab.frame.origin.x + lab.frame.size.width + sp, 0);
    }
    

}

-(void) titleLabClick:(UITapGestureRecognizer *) tap
{
    UILabel *lab = (UILabel *) tap.view;
    
    if (lab == _selectLab) {
        return;
    }
    
    [self titleChangWith:lab.tag];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:lab.tag inSection:0];
    [_contentCollextView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

-(void) titleChangWith:(NSInteger) page
{
     UILabel *lab = _labAry[page];
        lab.textColor = _style.titleSelectColor;
    _selectLab.textColor = _style.titleNormalColor;
    _selectLab = lab;
    CGFloat offsetX = lab.center.x - _titleScrollView.bounds.size.width * 0.5;
    if(offsetX < 0)
    {
        offsetX = 0;
    }
    
    if(offsetX > _titleScrollView.contentSize.width - self.bounds.size.width)
    {
        offsetX = _titleScrollView.contentSize.width - self.bounds.size.width;
    }
    [_titleScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
    if(_style.isShoeBottomLine)
    {
        
        
        [UIView animateWithDuration:0.2 animations:^{
            CGRect rect2 = _bottomLine.frame;
            rect2.origin.x = lab.frame.origin.x;
            rect2.size.width = lab.frame.size.width;
            _bottomLine.frame = rect2;
            
        }];
    }

}

-(void) setupContentView
{
    
    for (UIViewController *vc in _childVCs) {
        [_parentVc addChildViewController:vc];
    }
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.frame.size.width, self.frame.size.height - _style.titleViewHeight);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    
    _contentCollextView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, _style.titleViewHeight, self.frame.size.width, self.frame.size.height - _style.titleViewHeight) collectionViewLayout:layout];
    _contentCollextView.dataSource = self;
    _contentCollextView.delegate = self;
    [_contentCollextView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ID];
    _contentCollextView.pagingEnabled = YES;
    _contentCollextView.showsHorizontalScrollIndicator = NO;
    _contentCollextView.bounces = NO;
    [self addSubview:_contentCollextView];
    
}

#pragma mark - UICollectionView
-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _childVCs.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    for (UIView *subview in cell.contentView.subviews) {
        [subview removeFromSuperview];
    }
    
    UIViewController *vc = _childVCs[indexPath.item];
    vc.view.frame = cell.contentView.bounds;
    [cell.contentView addSubview:vc.view];
    return cell;
}


-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if(scrollView == _contentCollextView)
    {
        NSInteger page = _contentCollextView.contentOffset.x / _contentCollextView.bounds.size.width;
        [self titleChangWith:page];
    }
    
}




@end
